home *** CD-ROM | disk | FTP | other *** search
/ One Click 11 / OneClick11.iso / Bancos de Dados / Conversao / Mysql2Excel / Setup.exe / Mysql2Excel.exe / imputil.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-06-23  |  19.4 KB  |  536 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''
  5. Import utilities
  6.  
  7. Exported classes:
  8.     ImportManager   Manage the import process
  9.  
  10.     Importer        Base class for replacing standard import functions
  11.     BuiltinImporter Emulate the import mechanism for builtin and frozen modules
  12.  
  13.     DynLoadSuffixImporter
  14. '''
  15. import imp
  16. import sys
  17. import __builtin__
  18. import struct
  19. import marshal
  20. __all__ = [
  21.     'ImportManager',
  22.     'Importer',
  23.     'BuiltinImporter']
  24. _StringType = type('')
  25. _ModuleType = type(sys)
  26.  
  27. class ImportManager:
  28.     '''Manage the import process.'''
  29.     
  30.     def install(self, namespace = vars(__builtin__)):
  31.         '''Install this ImportManager into the specified namespace.'''
  32.         if isinstance(namespace, _ModuleType):
  33.             namespace = vars(namespace)
  34.         
  35.         self.previous_importer = namespace['__import__']
  36.         self.namespace = namespace
  37.         namespace['__import__'] = self._import_hook
  38.  
  39.     
  40.     def uninstall(self):
  41.         '''Restore the previous import mechanism.'''
  42.         self.namespace['__import__'] = self.previous_importer
  43.  
  44.     
  45.     def add_suffix(self, suffix, importFunc):
  46.         if not __debug__ and callable(importFunc):
  47.             raise AssertionError
  48.         self.fs_imp.add_suffix(suffix, importFunc)
  49.  
  50.     clsFilesystemImporter = None
  51.     
  52.     def __init__(self, fs_imp = None):
  53.         if not _os_stat:
  54.             _os_bootstrap()
  55.         
  56.         if not fs_imp:
  57.             if not self.clsFilesystemImporter:
  58.                 pass
  59.             cls = _FilesystemImporter
  60.             fs_imp = cls()
  61.         
  62.         self.fs_imp = fs_imp
  63.         for desc in imp.get_suffixes():
  64.             if desc[2] == imp.C_EXTENSION:
  65.                 self.add_suffix(desc[0], DynLoadSuffixImporter(desc).import_file)
  66.             
  67.         
  68.         self.add_suffix('.py', py_suffix_importer)
  69.  
  70.     
  71.     def _import_hook(self, fqname, globals = None, locals = None, fromlist = None):
  72.         '''Python calls this hook to locate and import a module.'''
  73.         parts = fqname.split('.')
  74.         parent = self._determine_import_context(globals)
  75.         if parent:
  76.             module = parent.__importer__._do_import(parent, parts, fromlist)
  77.             if module:
  78.                 return module
  79.             
  80.         
  81.         
  82.         try:
  83.             top_module = sys.modules[parts[0]]
  84.         except KeyError:
  85.             top_module = self._import_top_module(parts[0])
  86.             if not top_module:
  87.                 raise ImportError, 'No module named ' + fqname
  88.             
  89.         except:
  90.             not top_module
  91.  
  92.         if len(parts) == 1:
  93.             if not fromlist:
  94.                 return top_module
  95.             
  96.             if not top_module.__dict__.get('__ispkg__'):
  97.                 return top_module
  98.             
  99.         
  100.         importer = top_module.__dict__.get('__importer__')
  101.         if importer:
  102.             return importer._finish_import(top_module, parts[1:], fromlist)
  103.         
  104.         if len(parts) == 2 and hasattr(top_module, parts[1]):
  105.             return top_module
  106.         
  107.         raise ImportError, 'No module named ' + fqname
  108.  
  109.     
  110.     def _determine_import_context(self, globals):
  111.         '''Returns the context in which a module should be imported.
  112.  
  113.         The context could be a loaded (package) module and the imported module
  114.         will be looked for within that package. The context could also be None,
  115.         meaning there is no context -- the module should be looked for as a
  116.         "top-level" module.
  117.         '''
  118.         if not globals or not globals.get('__importer__'):
  119.             return None
  120.         
  121.         parent_fqname = globals['__name__']
  122.         if globals['__ispkg__']:
  123.             parent = sys.modules[parent_fqname]
  124.             if not __debug__ and globals is parent.__dict__:
  125.                 raise AssertionError
  126.             return parent
  127.         
  128.         i = parent_fqname.rfind('.')
  129.         if i == -1:
  130.             return None
  131.         
  132.         parent_fqname = parent_fqname[:i]
  133.         parent = sys.modules[parent_fqname]
  134.         if not __debug__ and parent.__name__ == parent_fqname:
  135.             raise AssertionError
  136.         return parent
  137.  
  138.     
  139.     def _import_top_module(self, name):
  140.         for item in sys.path:
  141.             if isinstance(item, _StringType):
  142.                 module = self.fs_imp.import_from_dir(item, name)
  143.             else:
  144.                 module = item.import_top(name)
  145.             if module:
  146.                 return module
  147.             
  148.         
  149.         return None
  150.  
  151.     
  152.     def _reload_hook(self, module):
  153.         '''Python calls this hook to reload a module.'''
  154.         importer = module.__dict__.get('__importer__')
  155.         if not importer:
  156.             pass
  157.         
  158.         raise SystemError, 'reload not yet implemented'
  159.  
  160.  
  161.  
  162. class Importer:
  163.     '''Base class for replacing standard import functions.'''
  164.     
  165.     def import_top(self, name):
  166.         '''Import a top-level module.'''
  167.         return self._import_one(None, name, name)
  168.  
  169.     
  170.     def _finish_import(self, top, parts, fromlist):
  171.         bottom = self._load_tail(top, parts)
  172.         if not fromlist:
  173.             return top
  174.         
  175.         if bottom.__ispkg__:
  176.             self._import_fromlist(bottom, fromlist)
  177.         
  178.         return bottom
  179.  
  180.     
  181.     def _import_one(self, parent, modname, fqname):
  182.         '''Import a single module.'''
  183.         
  184.         try:
  185.             return sys.modules[fqname]
  186.         except KeyError:
  187.             pass
  188.  
  189.         result = self.get_code(parent, modname, fqname)
  190.         if result is None:
  191.             return None
  192.         
  193.         module = self._process_result(result, fqname)
  194.         if parent:
  195.             setattr(parent, modname, module)
  196.         
  197.         return module
  198.  
  199.     
  200.     def _process_result(self, .2, fqname):
  201.         (ispkg, code, values) = .2
  202.         is_module = isinstance(code, _ModuleType)
  203.         if is_module:
  204.             module = code
  205.         else:
  206.             module = imp.new_module(fqname)
  207.         module.__importer__ = self
  208.         module.__ispkg__ = ispkg
  209.         module.__dict__.update(values)
  210.         sys.modules[fqname] = module
  211.         if not is_module:
  212.             exec code in module.__dict__
  213.         
  214.         module = sys.modules[fqname]
  215.         module.__name__ = fqname
  216.         return module
  217.  
  218.     
  219.     def _load_tail(self, m, parts):
  220.         '''Import the rest of the modules, down from the top-level module.
  221.  
  222.         Returns the last module in the dotted list of modules.
  223.         '''
  224.         for part in parts:
  225.             fqname = '%s.%s' % (m.__name__, part)
  226.             m = self._import_one(m, part, fqname)
  227.             if not m:
  228.                 raise ImportError, 'No module named ' + fqname
  229.             
  230.         
  231.         return m
  232.  
  233.     
  234.     def _import_fromlist(self, package, fromlist):
  235.         '''Import any sub-modules in the "from" list.'''
  236.         if '*' in fromlist:
  237.             fromlist = list(fromlist) + list(package.__dict__.get('__all__', []))
  238.         
  239.         for sub in fromlist:
  240.             if sub != '*' and not hasattr(package, sub):
  241.                 subname = '%s.%s' % (package.__name__, sub)
  242.                 submod = self._import_one(package, sub, subname)
  243.                 if not submod:
  244.                     raise ImportError, 'cannot import name ' + subname
  245.                 
  246.             
  247.         
  248.  
  249.     
  250.     def _do_import(self, parent, parts, fromlist):
  251.         '''Attempt to import the module relative to parent.
  252.  
  253.         This method is used when the import context specifies that <self>
  254.         imported the parent module.
  255.         '''
  256.         top_name = parts[0]
  257.         top_fqname = parent.__name__ + '.' + top_name
  258.         top_module = self._import_one(parent, top_name, top_fqname)
  259.         if not top_module:
  260.             return None
  261.         
  262.         return self._finish_import(top_module, parts[1:], fromlist)
  263.  
  264.     
  265.     def get_code(self, parent, modname, fqname):
  266.         '''Find and retrieve the code for the given module.
  267.  
  268.         parent specifies a parent module to define a context for importing. It
  269.         may be None, indicating no particular context for the search.
  270.  
  271.         modname specifies a single module (not dotted) within the parent.
  272.  
  273.         fqname specifies the fully-qualified module name. This is a
  274.         (potentially) dotted name from the "root" of the module namespace
  275.         down to the modname.
  276.         If there is no parent, then modname==fqname.
  277.  
  278.         This method should return None, or a 3-tuple.
  279.  
  280.         * If the module was not found, then None should be returned.
  281.  
  282.         * The first item of the 2- or 3-tuple should be the integer 0 or 1,
  283.             specifying whether the module that was found is a package or not.
  284.  
  285.         * The second item is the code object for the module (it will be
  286.             executed within the new module\'s namespace). This item can also
  287.             be a fully-loaded module object (e.g. loaded from a shared lib).
  288.  
  289.         * The third item is a dictionary of name/value pairs that will be
  290.             inserted into new module before the code object is executed. This
  291.             is provided in case the module\'s code expects certain values (such
  292.             as where the module was found). When the second item is a module
  293.             object, then these names/values will be inserted *after* the module
  294.             has been loaded/initialized.
  295.         '''
  296.         raise RuntimeError, 'get_code not implemented'
  297.  
  298.  
  299. if not __debug__ and 'c':
  300.     pass
  301. _suffix_char = 'o'
  302. _suffix = '.py' + _suffix_char
  303.  
  304. def _compile(pathname, timestamp):
  305.     """Compile (and cache) a Python source file.
  306.  
  307.     The file specified by <pathname> is compiled to a code object and
  308.     returned.
  309.  
  310.     Presuming the appropriate privileges exist, the bytecodes will be
  311.     saved back to the filesystem for future imports. The source file's
  312.     modification timestamp must be provided as a Long value.
  313.     """
  314.     codestring = open(pathname, 'r').read()
  315.     if codestring and codestring[-1] != '\n':
  316.         codestring = codestring + '\n'
  317.     
  318.     code = __builtin__.compile(codestring, pathname, 'exec')
  319.     
  320.     try:
  321.         f = open(pathname + _suffix_char, 'wb')
  322.     except IOError:
  323.         pass
  324.  
  325.     f.write('\x00\x00\x00\x00')
  326.     f.write(struct.pack('<I', timestamp))
  327.     marshal.dump(code, f)
  328.     f.flush()
  329.     f.seek(0, 0)
  330.     f.write(imp.get_magic())
  331.     f.close()
  332.     return code
  333.  
  334. _os_stat = _os_path_join = None
  335.  
  336. def _os_bootstrap():
  337.     """Set up 'os' module replacement functions for use during import bootstrap."""
  338.     global _os_stat, _os_path_join
  339.     names = sys.builtin_module_names
  340.     join = None
  341.     if 'posix' in names:
  342.         sep = '/'
  343.         stat = stat
  344.         import posix
  345.     elif 'nt' in names:
  346.         sep = '\\'
  347.         stat = stat
  348.         import nt
  349.     elif 'dos' in names:
  350.         sep = '\\'
  351.         stat = stat
  352.         import dos
  353.     elif 'os2' in names:
  354.         sep = '\\'
  355.         stat = stat
  356.         import os2
  357.     elif 'mac' in names:
  358.         stat = stat
  359.         import mac
  360.         
  361.         def join(a, b):
  362.             if a == '':
  363.                 return b
  364.             
  365.             path = s
  366.             if ':' not in a:
  367.                 a = ':' + a
  368.             
  369.             if a[-1:] != ':':
  370.                 a = a + ':'
  371.             
  372.             return a + b
  373.  
  374.     else:
  375.         raise ImportError, 'no os specific module found'
  376.     if join is None:
  377.         
  378.         def join(a, b, sep = sep):
  379.             if a == '':
  380.                 return b
  381.             
  382.             lastchar = a[-1:]
  383.             if lastchar == '/' or lastchar == sep:
  384.                 return a + b
  385.             
  386.             return a + sep + b
  387.  
  388.     
  389.     _os_stat = stat
  390.     _os_path_join = join
  391.  
  392.  
  393. def _os_path_isdir(pathname):
  394.     '''Local replacement for os.path.isdir().'''
  395.     
  396.     try:
  397.         s = _os_stat(pathname)
  398.     except OSError:
  399.         return None
  400.  
  401.     return s[0] & 61440 == 16384
  402.  
  403.  
  404. def _timestamp(pathname):
  405.     '''Return the file modification time as a Long.'''
  406.     
  407.     try:
  408.         s = _os_stat(pathname)
  409.     except OSError:
  410.         return None
  411.  
  412.     return long(s[8])
  413.  
  414.  
  415. class BuiltinImporter(Importer):
  416.     
  417.     def get_code(self, parent, modname, fqname):
  418.         if parent:
  419.             return None
  420.         
  421.         if imp.is_builtin(modname):
  422.             type = imp.C_BUILTIN
  423.         elif imp.is_frozen(modname):
  424.             type = imp.PY_FROZEN
  425.         else:
  426.             return None
  427.         module = imp.load_module(modname, None, modname, ('', '', type))
  428.         return (0, module, { })
  429.  
  430.  
  431.  
  432. class _FilesystemImporter(Importer):
  433.     
  434.     def __init__(self):
  435.         self.suffixes = []
  436.  
  437.     
  438.     def add_suffix(self, suffix, importFunc):
  439.         if not __debug__ and callable(importFunc):
  440.             raise AssertionError
  441.         self.suffixes.append((suffix, importFunc))
  442.  
  443.     
  444.     def import_from_dir(self, dir, fqname):
  445.         result = self._import_pathname(_os_path_join(dir, fqname), fqname)
  446.         if result:
  447.             return self._process_result(result, fqname)
  448.         
  449.         return None
  450.  
  451.     
  452.     def get_code(self, parent, modname, fqname):
  453.         if not __debug__ and parent:
  454.             raise AssertionError
  455.         return self._import_pathname(_os_path_join(parent.__pkgdir__, modname), fqname)
  456.  
  457.     
  458.     def _import_pathname(self, pathname, fqname):
  459.         if _os_path_isdir(pathname):
  460.             result = self._import_pathname(_os_path_join(pathname, '__init__'), fqname)
  461.             if result:
  462.                 values = result[2]
  463.                 values['__pkgdir__'] = pathname
  464.                 values['__path__'] = [
  465.                     pathname]
  466.                 return (1, result[1], values)
  467.             
  468.             return None
  469.         
  470.         for suffix, importFunc in self.suffixes:
  471.             filename = pathname + suffix
  472.             
  473.             try:
  474.                 finfo = _os_stat(filename)
  475.             except OSError:
  476.                 pass
  477.  
  478.             return importFunc(filename, finfo, fqname)
  479.         
  480.         return None
  481.  
  482.  
  483.  
  484. def py_suffix_importer(filename, finfo, fqname):
  485.     file = filename[:-3] + _suffix
  486.     t_py = long(finfo[8])
  487.     t_pyc = _timestamp(file)
  488.     code = None
  489.     if t_pyc is not None and t_pyc >= t_py:
  490.         f = open(file, 'rb')
  491.         if f.read(4) == imp.get_magic():
  492.             t = struct.unpack('<I', f.read(4))[0]
  493.             if t == t_py:
  494.                 code = marshal.load(f)
  495.             
  496.         
  497.         f.close()
  498.     
  499.     if code is None:
  500.         file = filename
  501.         code = _compile(file, t_py)
  502.     
  503.     return (0, code, {
  504.         '__file__': file })
  505.  
  506.  
  507. class DynLoadSuffixImporter:
  508.     
  509.     def __init__(self, desc):
  510.         self.desc = desc
  511.  
  512.     
  513.     def import_file(self, filename, finfo, fqname):
  514.         fp = open(filename, self.desc[1])
  515.         module = imp.load_module(fqname, fp, filename, self.desc)
  516.         module.__file__ = filename
  517.         return (0, module, { })
  518.  
  519.  
  520.  
  521. def _print_importers():
  522.     items = sys.modules.items()
  523.     items.sort()
  524.     for name, module in items:
  525.         if module:
  526.             print name, module.__dict__.get('__importer__', '-- no importer')
  527.         else:
  528.             print name, '-- non-existent module'
  529.     
  530.  
  531.  
  532. def _test_revamp():
  533.     ImportManager().install()
  534.     sys.path.insert(0, BuiltinImporter())
  535.  
  536.